/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package User;

import Bean.userBeanRemote;
import Objects.User;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import javax.imageio.ImageIO;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.imgscalr.Scalr;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

/**
 *
 * @author ntfsbk
 */
public class profileController extends MultiActionController {

    InitialContext context;
    String folderPath = "/ImageFileData";

    public ModelAndView profile(HttpServletRequest request, HttpServletResponse response) throws Exception {

        ModelAndView view = new ModelAndView("profile");
        try {
            context = new InitialContext();
            userBeanRemote userBean = (userBeanRemote) context.lookup("userBean");

            HttpSession session = request.getSession();
            int userId = (Integer) session.getAttribute("userId");
            User user = userBean.getUserInfoByUserId(userId);

            String userName = user.getUserName();
            view.addObject("userName", userName);
            String email = user.getEmail();
            view.addObject("email", email);
            String gender = user.getGender();
            view.addObject("gender", gender);
            String birthDay = user.getBirth();
            view.addObject("birthDate", birthDay);
            int year = Integer.parseInt(birthDay.substring(0, 4));
            view.addObject("year", year);
            int month = Integer.parseInt(birthDay.substring(5, 7));
            view.addObject("month", month);
            int day = Integer.parseInt(birthDay.substring(8));
            view.addObject("day", day);
            int profileAlbumId = user.getProfileAlbumId();
            String thumbnailFileName = userBean.getFileNameThumbnailOfAlbums(profileAlbumId);
            view.addObject("thumbFileName", thumbnailFileName);

            String password = (String) request.getParameter("password");
            String passFlag = "new";
            if (password != null) {
                String new_password = (String) request.getParameter("new_password");
                String retype_new = (String) request.getParameter("retype_new");
                String oldPass = user.getPassword();

                if (oldPass.equals(password) == false) {
                    passFlag = "wrongPass";
                } else if (new_password.equals("") || retype_new.equals("")) {
                    passFlag = "emptyPass";
                } else if (new_password.equals(retype_new) == false) {
                    passFlag = "passnotMatch";
                } else {
                    boolean result = userBean.updatePass(retype_new, userId);
                    if (result == true) {
                        passFlag = "updatePassSucess";
                    } else {
                        passFlag = "updatePassFail";
                    }
                }

            }

            view.addObject("passFlag", passFlag);
        } catch (NamingException ex) {
            throw ex;
        }
        return view;
    }

    public void getThumb(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ServletContext sc = request.getSession().getServletContext();
        File fileUploadPath = new File(sc.getRealPath(folderPath));
        File file = new File(fileUploadPath, request.getParameter("getthumb"));

        if (file.exists()) {
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    String sizeString = request.getParameter("size");
                    BufferedImage thumb;
                    if (sizeString == null) {
                        thumb = Scalr.resize(im, 194, 194);
                    } else {
                        int size = Integer.parseInt(sizeString);
                        thumb = Scalr.resize(im, size, size);
                    }
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    ServletOutputStream srvos = response.getOutputStream();
                    response.setContentLength(os.size());
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                    os.writeTo(srvos);
                    srvos.flush();
                    srvos.close();
                }
            }
        }

    }

    public void updateGender(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            context = new InitialContext();
            userBeanRemote userBean = (userBeanRemote) context.lookup("userBean");

            String gender = (String) request.getParameter("gender");
            HttpSession session = request.getSession();
            int userId = (Integer) session.getAttribute("userId");

            boolean result = userBean.updateGender(gender, userId);

            response.setContentType("html/textplain");
            if (result) {
                response.getWriter().write("true");
            } else {
                response.getWriter().write("false");
            }
        } catch (Exception e) {
            throw e;
        }
    }

    public void updateBirth(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            context = new InitialContext();
            userBeanRemote userBean = (userBeanRemote) context.lookup("userBean");

            String year = (String) request.getParameter("year");
            String month = (String) request.getParameter("month");
            String date = (String) request.getParameter("date");
            String birth = year + "-" + month + "-" + date;

            HttpSession session = request.getSession();
            int userId = (Integer) session.getAttribute("userId");

            boolean result = userBean.updateBirth(birth, userId);

            response.setContentType("html/textplain");
            if (result) {
                response.getWriter().write("true");
            } else {
                response.getWriter().write("false");
            }
        } catch (Exception e) {
            throw e;
        }
    }

    private String getMimeType(File file) {
        String mimetype = "";
        if (file.exists()) {
//            URLConnection uc = new URL("file://" + file.getAbsolutePath()).openConnection();
//            String mimetype = uc.getContentType();
//            MimetypesFIleTypeMap gives PNG as application/octet-stream, but it seems so does URLConnection
//            have to make dirty workaround
            if (getSuffix(file.getName()).equalsIgnoreCase("png")) {
                mimetype = "image/png";
            } else {
                javax.activation.MimetypesFileTypeMap mtMap = new javax.activation.MimetypesFileTypeMap();
                mimetype = mtMap.getContentType(file);
            }
        }
        System.out.println("mimetype: " + mimetype);
        return mimetype;
    }

    private String getSuffix(String filename) {
        String suffix = "";
        int pos = filename.lastIndexOf('.');
        if (pos > 0 && pos < filename.length() - 1) {
            suffix = filename.substring(pos + 1);
        }
        return suffix;
    }
}
